package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送手机验证码
     * @param phone
     * @param session
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            //无效手机号格式
            throw new RuntimeException("手机号格式错误！");
        }
        //todo 限制短信发送（防止频繁发送短信）
        //2.生成验证码
        String code = RandomUtil.randomNumbers(6);
        //3.将验证码保存到redis中
        //session.setAttribute("code",code);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4.发送验证码
        log.warn("发送验证码成功:验证码：{}",code);
        return Result.ok();

    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号 todo 直接校验与之前发送验证码手机号是否相同更合适
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            //无效手机号格式
            throw new RuntimeException("手机号格式错误！");
        }
        //2.校验验证码
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        //Object code = session.getAttribute("code");
        if(code==null || !loginForm.getCode().equals(code)){
            //不一致，报错
            return Result.fail("验证码错误");
        }
        //3.一致，根据手机号查询用户
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone,phone);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        if(user==null){
            //说明用户不存在，创建新用户，并保存到数据库
            log.info("用户不存在，创建新用户，用户手机号：{}",phone);
            user=new User();
            user.setPhone(phone); //存入手机号
            user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10)); //存入随机用户名
            userMapper.insert(user);
        }
        //4.存入redis
            //随机生成一个token作为key
        String token = UUID.randomUUID().toString(true);
            //将User对象转为Hash存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true) //设置非空忽略
                        .setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()) //设置字段值修改器
        );
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,userMap);
            //设置有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL,TimeUnit.MINUTES);
        //session.setAttribute("user", BeanUtil.copyProperties(user,UserDTO.class));
        //返回token
        return Result.ok(token);
    }
}






















